<template>
  <page-header-wrapper>
    <a-card :bordered="false">
      <a-form-model
        ref="vipForm"
        :model="vipForm"
        :rules="vipRules"
        :label-col="{ span: 3 }"
        :wrapper-col="{ span: 21 }"
      >
        <h4 style="margin-bottom: 10px">基础设置</h4>
        <a-form-model-item label="会员卡名称" prop="name">
          <a-input v-model="vipForm.name" placeholder="会员卡名称" style="width: 460px" />
        </a-form-model-item>
        <a-form-model-item label="会员卡排序" prop="sort">
          <a-input-number v-model="vipForm.sort" :min="0" style="width: 460px" />
        </a-form-model-item>
        <a-form-model-item label="会员卡图片" prop="image">
          <cyyUploadImg
            @uploadSuccess="
              (e) => {
                vipForm.image = e.data
              }
            "
            @deleteImg="vipForm.image = ''"
            :imgSrc="vipForm.image"
            imgSizeText="670*310"
          >
          </cyyUploadImg>
        </a-form-model-item>
        <a-form-model-item label="会员卡背景" prop="bg_image">
          <cyyUploadImg
            @uploadSuccess="
              (e) => {
                vipForm.bg_image = e.data
              }
            "
            @deleteImg="vipForm.bg_image = ''"
            :imgSrc="vipForm.bg_image"
            imgSizeText="750*1334，背景与会员卡相匹配"
          >
          </cyyUploadImg>
        </a-form-model-item>
        <!-- <a-form-model-item label="开启自购返利" prop="give_self">
          <a-radio-group v-model="vipForm.give_self">
            <a-radio value="0"> 关闭 </a-radio>
            <a-radio value="1"> 开启 </a-radio>
          </a-radio-group>
        </a-form-model-item>
        <a-form-model-item label="自购返利比例" prop="self_info" v-if="vipForm.give_self == 1">
          <a-input
            v-model="vipForm.self_info"
            type="number"
            addon-after="%"
            placeholder="自购返利比例"
            style="width: 460px"
          />
        </a-form-model-item> -->
        <a-form-model-item label="购买方式" prop="get_type">
          <a-radio-group v-model="vipForm.get_type">
            <a-radio value="1"> 一次性付款 </a-radio>
            <a-radio value="2"> 注册赠送 </a-radio>
          </a-radio-group>
          <a-table
            :columns="buyTypeColumns"
            :rowKey="
              (r, i) => {
                return i
              }
            "
            :data-source="vipForm.sale_info"
            :pagination="false"
            style="margin-top: 10px"
            v-if="vipForm.get_type == 1"
          >
            <a-checkbox
              slot="choosed"
              slot-scope="scope"
              :checked="scope.choosed"
              @change="
                (e) => {
                  scope.choosed = e.target.checked
                }
              "
            >
            </a-checkbox>
            <span slot="type" slot-scope="text">
              {{ text == 'month' ? '月卡' : text == 'quarter' ? '季卡' : text == 'year' ? '年卡' : '永久会员卡' }}
            </span>
            <div slot="price" slot-scope="scope">
              <a-input addon-after="元" v-model="scope.price" style="width: 200px" placeholder="请输入购买金额" />
            </div>
            <a-input
              slot="name"
              slot-scope="scope"
              v-model="scope.name"
              style="width: 160px"
              placeholder="请输入名称"
            ></a-input>
          </a-table>
        </a-form-model-item>

        <a-divider />
        <h4 style="margin-bottom: 10px">开卡赠送</h4>
        <a-form-model-item label="开卡赠送" prop="give">
          <a-radio-group v-model="vipForm.give">
            <a-radio value="1"> 开启 </a-radio>
            <a-radio value="0"> 关闭 </a-radio>
          </a-radio-group>
        </a-form-model-item>
        <template v-if="vipForm.give == 1">
          <a-form-model-item label="优惠券" prop="give_coupon">
            <a-radio-group v-model="vipForm.give_coupon">
              <a-radio value="1"> 开启 </a-radio>
              <a-radio value="0"> 关闭 </a-radio>
            </a-radio-group>
            <div>
              <a-table
                :columns="couponColumns"
                :rowKey="
                  (r, i) => {
                    return i
                  }
                "
                :data-source="vipForm.coupon_info_detail"
                :pagination="false"
                style="margin-top: 10px"
                v-if="vipForm.give_coupon == 1"
              >
                <a-button
                  slot="action"
                  slot-scope="text, scope, index"
                  type="link"
                  @click="deleteCoupon(text, scope, index, 'coupon')"
                  >删除</a-button
                >
                <span slot="discount_type_text" slot-scope="text">
                  {{text == 1 ?'折扣券':'满减券'}}
                </span>
              </a-table>
              <a-button type="dashed" style="width: 100%; margin-top: 16px" @click="showAddCoupon = true">
                + 添加优惠券
              </a-button>
            </div>
          </a-form-model-item>
          <a-form-model-item label="核销卡" prop="give_verify">
            <a-radio-group v-model="vipForm.give_verify">
              <a-radio value="1"> 开启 </a-radio>
              <a-radio value="0"> 关闭 </a-radio>
            </a-radio-group>
            <div>
              <a-table
                :columns="cardColumns"
                :rowKey="
                  (r, i) => {
                    return i
                  }
                "
                :data-source="vipForm.verify_info_detail"
                :pagination="false"
                style="margin-top: 10px"
                v-if="vipForm.give_verify == 1"
              >
                <!-- 有效时间 -->
                <span slot="expire_day" slot-scope="text, record">
                  <span v-if="record.date_type == 1">{{ `领取后${text == 0 ? '永久有效' : text + '天有效'}` }}</span>
                  <span v-else-if="record.date_type == 2">{{ record.begin_time }}至{{ record.end_time }}</span>
                  <span v-else>{{ text }}</span>
                </span>
                <a-button
                  slot="action"
                  slot-scope="text, scope, index"
                  type="link"
                  @click="deleteCoupon(text, scope, index, 'verify')"
                  >删除</a-button
                >
              </a-table>
              <a-button type="dashed" style="width: 100%; margin-top: 16px" @click="showAddCard = true">
                + 添加核销卡
              </a-button>
            </div>
          </a-form-model-item>
        </template>
        <a-divider />
        <h4 style="margin-bottom: 10px">分销设置</h4>
        <a-form-model-item label="一级佣金" prop="commission_one">
          <a-input v-model="vipForm.commission_one" addon-after="%" placeholder="请输入佣金"/>
        </a-form-model-item>
        <a-form-model-item label="二级佣金" prop="commission_two">
          <a-input v-model="vipForm.commission_two" addon-after="%" placeholder="请输入佣金" />
        </a-form-model-item>
        <a-form-model-item label="三级佣金" prop="commission_three">
          <a-input v-model="vipForm.commission_three" addon-after="%" placeholder="请输入佣金" />
        </a-form-model-item>
        <h4 style="margin-bottom: 10px">权益设置</h4>
        <a-form-model-item label="权益说明" prop="right_status">
          <a-radio-group v-model="vipForm.right_status">
            <a-radio value="1"> 开启 </a-radio>
            <a-radio value="0"> 关闭 </a-radio>
          </a-radio-group>
          <a-table
            :columns="rightsColumns"
            :rowKey="
              (r, i) => {
                return i
              }
            "
            :data-source="vipForm.right_info"
            :pagination="false"
            style="margin-top: 10px"
            v-if="vipForm.right_status == 1"
          >
            <a-checkbox
              slot="choosed"
              slot-scope="scope"
              :checked="scope.choosed"
              @change="
                (e) => {
                  scope.choosed = e.target.checked
                }
              "
            >
            </a-checkbox>
            <div slot="type" slot-scope="scope" class="rightName">
              <span>{{ scope.name }}</span>
              <span>{{ scope.explanation }}</span>
            </div>
            <div slot="icon" slot-scope="scope">
              <cyyUploadImg
                @uploadSuccess="
                  (e) => {
                    scope.icon = e.data
                  }
                "
                @deleteImg="scope.icon = ''"
                :imgSrc="scope.icon"
                imgSizeText="84*84"
                boxWidth="48"
                iconSize="14"
                uploadText="上传"
                :showSize="false"
              >
              </cyyUploadImg>
            </div>
            <a-input
              slot="name"
              slot-scope="scope"
              v-model="scope.custom_name"
              style="width: 200px"
              placeholder="请输入权益名称"
            ></a-input>
            <a-input
              slot="introduce"
              slot-scope="scope"
              v-model="scope.custom_explanation"
              style="width: 200px"
              placeholder="请输入权益介绍"
            ></a-input>
          </a-table>
        </a-form-model-item>
        <a-form-model-item label="权益详情" prop="right_default">
          <WangEditor
            :value="content"
            @change="
              (e) => {
                vipForm.right_default = e
              }
            "
          ></WangEditor>
          <a-textarea :hidden="true" v-model="vipForm.right_default" />
        </a-form-model-item>
        <a-form-model-item :wrapper-col="{ span: 14, offset: 4 }">
          <a-button type="primary" @click="creatVip"> 保存 </a-button>
          <a-button style="margin-left: 10px" @click="$router.back()"> 取消 </a-button>
        </a-form-model-item>
      </a-form-model>

      <!-- 添加优惠券的弹窗 -->
      <a-modal v-model="showAddCoupon" title="选择优惠券" width="800px" :footer="null">
        <div style="display: flex; align-items: center; margin-bottom: 20px">
          <a-input style="width: 300px" v-model="couponParam.search_shop_name" placeholder="请输入店铺名称"></a-input>
          <a-button style="margin-left: 20px" type="primary" @click="getCouponList">查询</a-button>
        </div>
        <a-table
          :rowKey="
            (r, i) => {
              return r.id
            }
          "
          :pagination="{
            total: this.couponCount,
            showSizeChanger: false,
            onChange: this.couponPageChange,
          }"
          :columns="couponListColumns"
          :data-source="couponList"
          :scroll="{ x: 'max-content' }"
        >
          <span slot="min_price" slot-scope="text"> {{ text }}元 </span>

          <!-- 优惠券金额 -->
          <span slot="sub_price" slot-scope="text">{{ text }}元</span>

          <!-- 折扣率 -->
          <span slot="discount" slot-scope="text">{{ text }}折</span>

          <!-- 已领 -->
          <div slot="total_count" slot-scope="text, item">
            <span>{{ item.receive_count }}</span>
          </div>

          <!-- 剩余 -->
          <div slot="surplus_count" slot-scope="text">
            <span v-if="text > 0">{{ text }}</span>
            <span v-else>无限制</span>
          </div>

          <!-- 有效期 -->
          <div slot="expire_type" slot-scope="text, item">
            <span v-if="item.expire_type == 1 && item.expire_day != 0">
              领卷后当日起{{ item.expire_day }}天内可用
            </span>
            <span v-else-if="item.expire_type == 1 && item.expire_day == 0">永久生效</span>
            <span v-if="item.expire_type == 2">{{ item.begin_time }}至{{ item.end_time }}</span>
          </div>

          <!-- 优惠卷数量 -->
          <div slot="coupon_status" slot-scope="text">
            <div v-if="text == 0" class="coupon-status-1">未开始</div>
            <div v-if="text == 1" class="coupon-status-1">进行中</div>
            <div v-if="text == 2" class="coupon-status-2">已结束</div>
          </div>

          <!-- 操作按钮 -->
          <span slot="action" slot-scope="text, record">
            <a-button type="link" @click="chooseCoupon(record, 'coupon')">选择</a-button>
          </span>
        </a-table>
      </a-modal>
      <!-- 添加优惠券的弹窗 -->
      <a-modal v-model="showAddCard" title="选择卡券" width="800px" :footer="null">
        <div style="display: flex; align-items: center; margin-bottom: 20px">
          <a-input style="width: 300px" v-model="verifyParam.search_shop_name" placeholder="请输入店铺名称"></a-input>
          <a-button style="margin-left: 20px" type="primary" @click="getVerifyList">查询</a-button>
        </div>
        <a-table
          :rowKey="
            (r, i) => {
              return r.id
            }
          "
          :pagination="{
            total: this.verifyCount,
            showSizeChanger: false,
            onChange: this.verifyPageChange,
          }"
          :columns="verifyListColumns"
          :data-source="verifyList"
          :scroll="{ x: 'max-content' }"
        >
          <span slot="name" slot-scope="text, item">
            <div class="flex">
              <img
                :src="item.pic_url"
                style="width: 45px; height: 45px; border-radius: 5px; margin-right: 10px"
                alt=""
              />
              <div>
                <div>{{ item.name }}</div>
                <!-- <div style="color: #999">{{ item.type }}</div> -->
                <span v-for="item1 in CARD_TYPE" :key="item1.value">
                  <span v-show="item.type == item1.value">
                    {{ item1.text }}
                  </span>
                </span>
              </div>
            </div>
          </span>

          <!-- 有效时间 -->
          <span slot="expire_day" slot-scope="text, record">
            <span v-if="record.date_type == 1">{{ `领取后${text == 0 ? '永久有效' : text + '天有效'}` }}</span>
            <span v-else-if="record.date_type == 2">{{ record.begin_time }}至{{ record.end_time }}</span>
            <span v-else>{{ text }}</span>
          </span>
          <!-- 操作按钮 -->
          <span slot="action" slot-scope="text, record">
            <a-button type="link" @click="chooseCoupon(record, 'verify')">选择</a-button>
          </span>
        </a-table>
      </a-modal>
    </a-card>
  </page-header-wrapper>
</template>

<script>
const buyTypeColumns = [
  {
    scopedSlots: {
      customRender: 'choosed',
    },
    width: 80,
  },
  {
    dataIndex: 'type',
    title: '会员卡名称',
    scopedSlots: {
      customRender: 'type',
    },
  },
  {
    title: '价格',
    scopedSlots: {
      customRender: 'price',
    },
  },
  {
    title: '自定义名称',
    scopedSlots: {
      customRender: 'name',
    },
  },
]
const couponColumns = [
  {
    dataIndex: 'store_name',
    title: '店铺名称',
  },
  {
    dataIndex: 'name',
    title: '优惠券名称',
  },
  {
    title: '最低消费',
    dataIndex: 'min_price',
  },
  {
    title: '优惠方式',
    dataIndex: 'discount_type',
    scopedSlots: {
      customRender: 'discount_type_text',
    },
  },
  {
    title: '折扣率',
    dataIndex: 'discount',
  },
  {
    title: '操作',
    scopedSlots: {
      customRender: 'action',
    },
  },
]
const cardColumns = [
  {
    dataIndex: 'store_name',
    title: '店铺名称',
  },
  {
    dataIndex: 'name',
    title: '卡券名称',
  },
  {
    title: '创建时间',
    dataIndex: 'created_at',
    sorter: (a, b) => new Date(a.created_at).getTime() - new Date(b.created_at).getTime(),
  },
  {
    title: '有效时间',
    dataIndex: 'expire_day',
    scopedSlots: {
      customRender: 'expire_day',
    },
  },
  {
    title: '操作',
    scopedSlots: {
      customRender: 'action',
    },
  },
]
const rightsColumns = [
  {
    scopedSlots: {
      customRender: 'choosed',
    },
    width: 80,
  },
  {
    title: '权益图标',
    scopedSlots: {
      customRender: 'icon',
    },
  },
  {
    title: '权益名称',
    scopedSlots: {
      customRender: 'type',
    },
  },
  {
    title: '自定义权益名称',
    scopedSlots: {
      customRender: 'name',
    },
  },
  {
    title: '自定义权益介绍',
    scopedSlots: {
      customRender: 'introduce',
    },
  },
]
const couponListColumns = [
  {
    title: '优惠券ID',
    dataIndex: 'id',
  },
  {
    title: '商城名称',
    dataIndex: 'store_name',
  },
  {
    title: '优惠券名称',
    dataIndex: 'name',
  },
  {
    title: '优惠方式',
    dataIndex: 'discount_type_text',
    scopedSlots: {
      customRender: 'discount_type_text',
    },
  },
  {
    title: '已领',
    dataIndex: 'total_count',
    scopedSlots: {
      customRender: 'total_count',
    },
    // 总数减剩余为已领   剩余默认是-1  总数默认是 -1
    sorter: (a, b) => a.total_count - a.surplus_count - (b.total_count - b.surplus_count),
  },
  {
    title: '剩余',
    dataIndex: 'surplus_count',
    scopedSlots: {
      customRender: 'surplus_count',
    },
    sorter: (a, b) => a.surplus_count - b.surplus_count,
  },

  {
    title: '有效时间',
    dataIndex: 'expire_type',
    scopedSlots: {
      customRender: 'expire_type',
    },
  },
  {
    title: '状态',
    dataIndex: 'coupon_status',
    scopedSlots: {
      customRender: 'coupon_status',
    },
  },
  {
    title: '操作',
    width: '200',
    dataIndex: 'action',
    scopedSlots: {
      customRender: 'action',
    },
  },
]
// 核销卡列表
const verifyListColumns = [
  {
    title: 'ID',
    dataIndex: 'id',
    width: 60,
  },
  {
    title: '商城名称',
    dataIndex: 'store_name',
  },
  {
    title: '卡劵名称',
    dataIndex: 'name',
    scopedSlots: {
      customRender: 'name',
    },
  },

  {
    title: '已发放数量',
    dataIndex: 'send_times',
    sorter: (a, b) => a.send_times - b.send_times,
  },

  {
    title: '创建时间',
    dataIndex: 'created_at',
    sorter: (a, b) => new Date(a.created_at).getTime() - new Date(b.created_at).getTime(),
  },
  {
    title: '有效时间',
    dataIndex: 'expire_day',
    scopedSlots: {
      customRender: 'expire_day',
    },
  },

  {
    title: '操作',
    dataIndex: 'action',
    scopedSlots: {
      customRender: 'action',
    },
  },
]
import { cyyUploadImg } from '@/components/CyyUi'
import { WangEditor } from '@/components'
import { addVipCard, editVipCard, rightsList, getVipCard, getList, verifyList } from '@/api/saas/marketing'
export default {
  components: {
    cyyUploadImg,
    WangEditor,
  },
  data() {
    return {
      vipForm: {
        id: '',
        name: '',
        sort: '',
        image: '',
        bg_image: '',
        get_type: '1',
        sale_info: [
          {
            choosed: false,
            type: 'month',
            price: '',
            name: '',
          },
          {
            choosed: false,
            type: 'quarter',
            price: '',
            name: '',
          },
          {
            choosed: false,
            type: 'year',
            price: '',
            name: '',
          },
          {
            choosed: false,
            type: 'perpetual',
            price: '',
            name: '',
          },
        ],
        give: '1',
        give_coupon: '1',
        give_verify: '1',
        coupon_info: [],
        coupon_info_detail: [],
        verify_info: [],
        verify_info_detail: [],
        commission_one: '',
        commission_two: '',
        commission_three: '',
        right_status: '1',
        right_ids: [],
        right_info: [],
        right_default: '',
        give_self: '0',
        self_info: '',
      },
      vipRules: {
        name: [{ required: true, message: '请输入会员卡名称', trigger: 'blur' }],
        image: [{ required: true, message: '请选择会员卡图片', trigger: 'change' }],
        bg_image: [{ required: true, message: '请输入会员卡背景', trigger: 'change' }],
      },
      buyTypeColumns,
      couponColumns,
      cardColumns,
      rightsColumns,
      couponListColumns,
      verifyListColumns,
      // 是否展示添加优惠券弹窗
      showAddCoupon: false,
      // 是否展示添加卡券弹窗
      showAddCard: false,
      // 添加优惠券的参数
      // 搜索参数
      couponParam: {
        name: '',
        search_shop_name: '',
        status: '-1',
        is_business: 1,
        pageNo: 1,
        pageSize: 10,
        business_type: 2,
      },
      // 卡券搜索参数
      verifyParam: {
        search_shop_name: '',
        pageNo: 1,
        pageSize: 10,
      },
      // 优惠券列表
      couponList: [],
      // 优惠券总数
      couponCount: 0,
      // 卡券列表
      verifyList: [],
      // 卡券总数
      verifyCount: 0,
      // 权益详情
      content: '',
    }
  },
  mounted() {
    console.log()
    if (!this.$route.query.id) {
      this.getRightsList()
    } else {
      this.getVipCard(this.$route.query.id)
    }
    this.getCouponList()
    this.getVerifyList()
  },
  methods: {
    // 获取会员卡权益列表
    async getRightsList() {
      const res = await rightsList()
      if (res.code == 0) {
        console.log(res)
        if (res.data && res.data.length) {
          res.data.forEach((item) => {
            item.choosed = false
            item.custom_name = ''
            item.icon = ''
            item.custom_explanation = ''
          })
          this.vipForm.right_info = res.data
        }
      }
    },
    // 点击创建会员卡
    creatVip() {
      this.$refs['vipForm'].validate(async (valid) => {
        if (valid) {
          if (this.vipForm.right_status == 1) {
            let arr = []
            this.vipForm.right_info.forEach((item) => {
              if (item.choosed) {
                arr.push(item.id)
              }
            })
            this.vipForm.right_ids = arr
          }
          if (this.vipForm.give == 1) {
            if (this.vipForm.give_coupon == 1) {
              let couponArr = []
              this.vipForm.coupon_info_detail.forEach((item) => {
                couponArr.push(item.id)
              })
              this.vipForm.coupon_info = couponArr
            }
            if (this.vipForm.give_verify == 1) {
              let verifyArr = []
              this.vipForm.verify_info_detail.forEach((item) => {
                verifyArr.push(item.id)
              })
              this.vipForm.verify_info = verifyArr
            }
          }
          this.vipForm.commission_type = '1'
          if (!this.vipForm.id) {
            const res = await addVipCard(this.vipForm)
            console.log(res)
            if (res.code == 0) {
              this.$router.back()
            }
          } else {
            const res = await editVipCard(this.vipForm)
            console.log(res)
            if (res.code == 0) {
              this.$router.back()
            }
          }
        }
      })
    },
    // 获取会员卡详情
    async getVipCard(id) {
      const res = await getVipCard({ id })
      if (res.code == 0) {
        console.log(res)
        this.vipForm = res.data
        this.content = res.data.right_default
      }
    },
    // 获取优惠券列表
    async getCouponList() {
      const res = await getList(this.couponParam)
      if (res.code == 0) {
        this.couponList = res.data.data
        this.couponCount = res.data.totalCount
      }
    },
    // 获取卡券列表
    async getVerifyList() {
      const res = await verifyList(this.verifyParam)
      if (res.code == 0) {
        this.verifyList = res.data.data
        this.verifyCount = res.data.totalCount
      }
    },
    // 优惠券页码改变
    couponPageChange(e) {
      this.couponParam.pageNo = e
      this.getCouponList()
    },
    // 卡券页码改变
    verifyPageChange(e) {
      this.verifyParam.pageNo = e
      this.getVerifyList()
    },
    // 选中优惠券
    chooseCoupon(record, type) {
      if (type == 'coupon') {
        this.vipForm.coupon_info_detail.push(record)
        this.showAddCoupon = false
      }
      if (type == 'verify') {
        this.vipForm.verify_info_detail.push(record)
        this.showAddCard = false
      }
    },
    deleteCoupon(text, scope, index, type) {
      if (type == 'coupon') {
        this.vipForm.coupon_info_detail.splice(index, 1)
      }
      if (type == 'verify') {
        this.vipForm.verify_info_detail.splice(index, 1)
      }
    },
  },
}
</script>

<style lang="less" scoped>
.rightName {
  display: flex;
  flex-direction: column;
  span:nth-child(1) {
    font-size: 14px;
    color: rgba(0, 0, 0, 0.65);
  }
  span:nth-child(2) {
    margin-top: 6px;
    font-size: 14px;
    color: rgba(0, 0, 0, 0.45);
  }
}
</style>